<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小区物业管理系统 - 公告管理</title>
    <!-- Tailwind CSS v3 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 统一的 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1e40af',
                        secondary: '#3b82f6',
                        accent: '#60a5fa',
                        light: '#f3f4f6',
                        dark: '#1e293b'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-gradient-blue {
                background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
        }
    </style>
    <!-- 内联样式替代@apply，避免CDN版本的限制 -->
    <style>
        /* 卡片样式 */
        .card {
            background-color: white;
            border-radius: 0.375rem;
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            border: 1px solid #f3f4f6;
        }
        .card-header {
            padding: 1rem;
            border-bottom: 1px solid #f3f4f6;
            font-weight: 500;
            color: #374151;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .card-body {
            padding: 1rem;
        }
        
        /* 导航链接样式 */
        .nav-link {
            display: flex;
            align-items: center;
            padding: 0.75rem 1rem;
            color: #4b5563;
            border-radius: 0.375rem;
            transition: all 300ms ease-in-out;
        }
        .nav-link:hover {
            background-color: #eff6ff;
            color: #2563eb;
        }
        .nav-link.active {
            background-color: #eff6ff;
            color: #2563eb;
        }
        .nav-link i {
            margin-right: 0.75rem;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            font-weight: 500;
            transition: all 300ms ease-in-out;
            outline: none;
        }
        .btn:focus {
            ring: 2px;
            ring-offset: 2px;
        }
        .btn-primary {
            background-color: #2563eb;
            color: white;
        }
        .btn-primary:hover {
            background-color: #1d4ed8;
        }
        .btn-primary:focus {
            ring-color: #3b82f6;
        }
        .btn-outline {
            border: 1px solid #d1d5db;
            color: #374151;
        }
        .btn-outline:hover {
            background-color: #f9fafb;
        }
        .btn-outline:focus {
            ring-color: #9ca3af;
        }
        .btn-sm {
            padding: 0.25rem 0.75rem;
            font-size: 0.875rem;
        }
        
        /* 徽章样式 */
        .badge {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            font-weight: 500;
            border-radius: 9999px;
        }
        .badge-success {
            background-color: #d1fae5;
            color: #065f46;
        }
        .badge-warning {
            background-color: #fef3c7;
            color: #92400e;
        }
        .badge-danger {
            background-color: #fee2e2;
            color: #991b1b;
        }
        .badge-info {
            background-color: #dbeafe;
            color: #1e40af;
        }
        
        /* 表格行悬停效果 */
        .table-row-hover:hover {
            background-color: #f9fafb;
            transition: all 300ms ease-in-out;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="flex h-screen overflow-hidden">
        <!-- 侧边导航栏 -->
        <aside class="w-64 bg-white shadow-sm hidden md:block">
            <div class="flex items-center justify-center h-16 border-b border-gray-100">
                <h2 class="text-lg font-semibold text-gray-800">物业管理系统</h2>
            </div>
            <nav class="p-4 space-y-1">
                <a href="dashboard.html" class="nav-link">
                    <i class="fa fa-dashboard"></i>
                    <span>控制面板</span>
                </a>
                <a href="community.html" class="nav-link">
                    <i class="fa fa-building"></i>
                    <span>小区管理</span>
                </a>
                <a href="owners.html" class="nav-link">
                    <i class="fa fa-users"></i>
                    <span>业主管理</span>
                </a>
                <a href="users.html" class="nav-link">
                    <i class="fa fa-user-circle"></i>
                    <span>用户管理</span>
                </a>
                <a href="maintenance.html" class="nav-link">
                    <i class="fa fa-wrench"></i>
                    <span>报修管理</span>
                </a>
                <a href="announcements.html" class="nav-link active">
                    <i class="fa fa-bullhorn"></i>
                    <span>公告管理</span>
                </a>
                <a href="fee_management.html" class="nav-link">
                    <i class="fa fa-credit-card"></i>
                    <span>物业收费管理</span>
                </a>
                <a href="settings.html" class="nav-link">
                    <i class="fa fa-cog"></i>
                    <span>系统设置</span>
                </a>
            </nav>
        </aside>
        
        <!-- 移动端侧边栏 -->
        <div id="mobile-sidebar" class="fixed inset-0 z-40 hidden">
            <div class="fixed inset-0 bg-gray-600 bg-opacity-75"></div>
            <div class="relative flex-1 flex flex-col max-w-xs w-full bg-white">
                <div class="absolute top-0 right-0 -mr-12 pt-2">
                    <button id="close-sidebar-button" class="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white">
                        <i class="fa fa-times text-white"></i>
                    </button>
                </div>
                <div class="flex-1 h-0 pt-5 pb-4 overflow-y-auto">
                    <div class="flex-shrink-0 flex items-center justify-center">
                        <h2 class="text-lg font-semibold text-gray-800">物业管理系统</h2>
                    </div>
                    <nav class="mt-5 px-2 space-y-1">
                        <a href="dashboard.html" class="nav-link">
                            <i class="fa fa-dashboard"></i>
                            <span>控制面板</span>
                        </a>
                        <a href="community.html" class="nav-link">
                            <i class="fa fa-building"></i>
                            <span>小区管理</span>
                        </a>
                        <a href="owners.html" class="nav-link">
                            <i class="fa fa-users"></i>
                            <span>业主管理</span>
                        </a>
                        <a href="maintenance.html" class="nav-link">
                            <i class="fa fa-wrench"></i>
                            <span>报修管理</span>
                        </a>
                        <a href="announcements.html" class="nav-link active">
                            <i class="fa fa-bullhorn"></i>
                            <span>公告管理</span>
                        </a>
                        <a href="fee_management.html" class="nav-link">
                            <i class="fa fa-credit-card"></i>
                                <span>物业收费管理</span>
                        </a>
                        <a href="settings.html" class="nav-link">
                            <i class="fa fa-cog"></i>
                            <span>系统设置</span>
                        </a>
                    </nav>
                </div>
            </div>
        </div>
        
        <!-- 主内容区域 -->
        <div class="flex-1 flex flex-col">
            <!-- 顶部导航栏 -->
            <header class="bg-white shadow-sm z-10">
                <div class="flex items-center justify-between h-16 px-6">
                    <!-- 移动端菜单按钮 -->
                    <button id="mobile-menu-button" class="md:hidden text-gray-500 hover:text-gray-700 focus:outline-none">
                        <i class="fa fa-bars"></i>
                    </button>
                    <div class="flex-1 max-w-md">
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                                <i class="fa fa-search text-gray-400"></i>
                            </span>
                            <input type="text" placeholder="搜索..." class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md">
                        </div>
                    </div>
                    <div class="flex items-center space-x-4">
                        <button class="relative text-gray-500">
                            <i class="fa fa-bell"></i>
                        </button>
                        <!-- 用户头像 -->
                        <div class="relative">
                            <button id="user-menu-button" class="flex items-center focus:outline-none">
                                <div class="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white">
                                    <i class="fa fa-user"></i>
                                </div>
                                <span class="ml-2 text-sm font-medium text-gray-700 hidden md:block">管理员</span>
                                <i class="fa fa-chevron-down ml-1 text-xs text-gray-400 hidden md:block"></i>
                            </button>
                            <!-- 用户下拉菜单 -->
                            <div id="user-menu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-20 hidden">
                                <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">个人资料</a>
                                <a href="#" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">设置</a>
                                <div class="border-t border-gray-100"></div>
                                <a href="login.html" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>
            
            <!-- 页面内容 -->
            <main class="flex-1 overflow-y-auto p-6">
                <div class="mb-6">
                    <h1 class="text-2xl font-bold text-gray-800 mb-4">公告管理</h1>
                    <button class="btn btn-primary">
                        <i class="fa fa-plus mr-2"></i>
                        发布公告
                    </button>
                </div>
                
                <!-- 公告列表 -->
                <div class="bg-white rounded-md shadow-sm border border-gray-100">
                    <div class="p-4 border-b border-gray-100">
                        <div class="flex items-center justify-between">
                            <h3 class="font-medium text-gray-700">公告列表</h3>
                            <div class="flex items-center space-x-2">
                                <input type="text" placeholder="搜索公告..." class="px-3 py-2 border border-gray-300 rounded-md">
                                <select class="border border-gray-300 rounded-md px-3 py-2">
                                    <option value="all">全部类型</option>
                                    <option value="notice">通知公告</option>
                                    <option value="activity">活动通知</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="min-w-full">
                            <thead>
                                <tr class="bg-gray-50">
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">标题</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">类型</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">公告状态</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">发布人</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">发布时间</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">过期时间</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">是否置顶</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">浏览次数</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">操作</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                <tr>
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium">关于小区停水通知的公告</div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="badge badge-info">通知公告</span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm">系统管理员</div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500">
                                        2023-05-01 08:00
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="badge badge-success">已发布</span>
                                    </td>
                                    <td class="px-6 py-4 text-sm font-medium">
                                        <a href="#" class="text-blue-600 mr-3">查看</a>
                                        <a href="#" class="text-green-600 mr-3">编辑</a>
                                        <a href="#" class="text-red-600">删除</a>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="px-6 py-4">
                                        <div class="text-sm font-medium">关于举办小区春季运动会的通知</div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="badge badge-info">活动通知</span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="text-sm">系统管理员</div>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500">
                                        2023-04-28 14:30
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="badge badge-success">已发布</span>
                                    </td>
                                    <td class="px-6 py-4 text-sm font-medium">
                                        <a href="#" class="text-blue-600 mr-3">查看</a>
                                        <a href="#" class="text-green-600 mr-3">编辑</a>
                                        <a href="#" class="text-red-600">删除</a>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="px-6 py-4 border-t border-gray-200">
                        <div class="flex items-center justify-between">
                            <div class="text-sm text-gray-700">
                                显示 1 到 2 共 15 条结果
                            </div>
                            <div class="flex space-x-2">
                                <button class="px-3 py-1 border border-gray-300 rounded-md" disabled>
                                    <i class="fa fa-chevron-left"></i>
                                </button>
                                <button class="px-3 py-1 bg-blue-600 text-white rounded-md">1</button>
                                <button class="px-3 py-1 border border-gray-300 rounded-md">2</button>
                                <button class="px-3 py-1 border border-gray-300 rounded-md">3</button>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script>
        // 简化实现，确保用户菜单交互正常工作
        window.addEventListener('load', function() {
            // 移动端菜单功能
            const mobileMenuButton = document.getElementById('mobile-menu-button');
            const mobileSidebar = document.getElementById('mobile-sidebar');
            const closeSidebarButton = document.getElementById('close-sidebar-button');
            
            if (mobileMenuButton && mobileSidebar) {
                mobileMenuButton.addEventListener('click', function() {
                    mobileSidebar.classList.remove('hidden');
                });
            }
            
            if (closeSidebarButton && mobileSidebar) {
                closeSidebarButton.addEventListener('click', function() {
                    mobileSidebar.classList.add('hidden');
                });
            }
            
            // 用户菜单功能
            const userMenuButton = document.getElementById('user-menu-button');
            const userMenu = document.getElementById('user-menu');
            
            if (userMenuButton && userMenu) {
                userMenuButton.onclick = function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    userMenu.classList.toggle('hidden');
                };
                
                // 点击页面其他地方关闭菜单
                document.addEventListener('click', function(e) {
                    if (!userMenuButton.contains(e.target) && !userMenu.contains(e.target)) {
                        userMenu.classList.add('hidden');
                    }
                });
            }
            
            // 初始化页面数据
            loadAnnouncements();
            
            // 搜索和筛选功能
            const searchInput = document.querySelector('input[placeholder="搜索公告..."]');
            const typeSelect = document.querySelector('select');
            
            if (searchInput) {
                searchInput.addEventListener('input', function() {
                    loadAnnouncements();
                });
            }
            
            if (typeSelect) {
                typeSelect.addEventListener('change', function() {
                    loadAnnouncements();
                });
            }
        });
        
        // 获取CSRF令牌
        function getCSRFToken() {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, 10) === 'csrftoken=') {
                        cookieValue = decodeURIComponent(cookie.substring(10));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        
        // 从API加载公告数据
        function loadAnnouncements() {
            // 获取搜索和筛选参数
            const searchInput = document.querySelector('input[placeholder="搜索公告..."]');
            const typeSelect = document.querySelector('select');
            const searchTerm = searchInput ? searchInput.value : '';
            const type = typeSelect ? typeSelect.value : 'all';
            
            // 构建API请求URL（使用完整路径）
            let url = 'http://127.0.0.1:8000/api/announcements/';
            const params = new URLSearchParams();
            
            if (type && type !== 'all') {
                params.append('type', type);
            }
            
            if (params.toString()) {
                url += '?' + params.toString();
            }
            
            console.log('请求URL:', url);
            
            // 发送API请求
            fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                credentials: 'include'
            })
            .then(response => {
                console.log('响应状态:', response.status);
                console.log('响应头:', response.headers);
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('获取到的数据:', data);
                // 如果返回的是分页数据
                const announcements = data.results || data;
                renderAnnouncements(announcements, searchTerm);
            })
            .catch(error => {
                console.error('获取公告数据失败:', error);
                // 显示错误提示
                const tableBody = document.querySelector('tbody');
                if (tableBody) {
                    tableBody.innerHTML = `
                        <tr>
                            <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                                获取公告数据失败，请稍后重试
                            </td>
                        </tr>
                    `;
                }
            });
        }
        
        // 渲染公告列表
        function renderAnnouncements(announcements, searchTerm) {
            const tableBody = document.querySelector('tbody');
            if (!tableBody) return;
            
            // 如果有搜索词，进行客户端筛选
            let filteredAnnouncements = announcements;
            if (searchTerm) {
                filteredAnnouncements = announcements.filter(announcement => 
                    announcement.title.toLowerCase().includes(searchTerm.toLowerCase())
                );
            }
            
            // 清空表格内容
            tableBody.innerHTML = '';
            
            // 如果没有数据，显示空状态
            if (filteredAnnouncements.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="9" class="px-6 py-4 text-center text-gray-500">
                            没有找到匹配的公告
                        </td>
                    </tr>
                `;
                return;
            }
            
            // 渲染公告数据
            filteredAnnouncements.forEach(announcement => {
                const tr = document.createElement('tr');
                tr.className = 'table-row-hover';
                
                // 获取状态标签和类型标签
                const statusBadge = announcement.status === 'published' || announcement.status === '已发布' || (!announcement.status && announcement.publish_date) 
                    ? '<span class="badge badge-success">已发布</span>'
                    : announcement.status === 'expired' || announcement.status === '已过期'
                    ? '<span class="badge badge-danger">已过期</span>'
                    : '<span class="badge badge-warning">草稿</span>';
                
                const typeBadge = getTypeBadge(announcement.type);
                
                // 格式化日期
                const publishDate = formatDate(announcement.publish_date);
                const expireDate = announcement.expire_date ? formatDate(announcement.expire_date) : '无';
                const isSticky = announcement.is_sticky ? '是' : '否';
                const viewsCount = announcement.views_count || 0;
                
                tr.innerHTML = `
                    <td class="px-6 py-4">
                        <div class="text-sm font-medium">${announcement.title}</div>
                    </td>
                    <td class="px-6 py-4">
                        ${typeBadge}
                    </td>
                    <td class="px-6 py-4">
                        ${statusBadge}
                    </td>
                    <td class="px-6 py-4">
                        <div class="text-sm">${announcement.publisher_name || '系统管理员'}</div>
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-500">
                        ${publishDate}
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-500">
                        ${expireDate}
                    </td>
                    <td class="px-6 py-4">
                        <span class="badge ${announcement.is_sticky ? 'badge-success' : 'badge-secondary'}">${isSticky}</span>
                    </td>
                    <td class="px-6 py-4 text-sm text-gray-500">
                        ${viewsCount}
                    </td>
                    <td class="px-6 py-4 text-sm font-medium">
                        <a href="#" class="text-blue-600 mr-3" onclick="viewAnnouncement(${announcement.id})">查看</a>
                        <a href="#" class="text-green-600 mr-3" onclick="editAnnouncement(${announcement.id})">编辑</a>
                        <a href="#" class="text-red-600" onclick="deleteAnnouncement(${announcement.id})">删除</a>
                    </td>
                `;
                
                tableBody.appendChild(tr);
            });
        }
        
        // 获取类型对应的徽章
        function getTypeBadge(type) {
            const typeMap = {
                'notice': { text: '通知公告', className: 'badge-info' },
                'event': { text: '活动通知', className: 'badge-info' },
                'bill': { text: '缴费通知', className: 'badge-info' },
                'maintenance': { text: '维修公告', className: 'badge-info' },
                'other': { text: '其他公告', className: 'badge-info' }
            };
            
            const typeInfo = typeMap[type] || { text: '其他公告', className: 'badge-info' };
            return `<span class="badge ${typeInfo.className}">${typeInfo.text}</span>`;
        }
        
        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 查看公告详情
        function viewAnnouncement(id) {
            alert(`查看公告ID: ${id}`);
            // 实际项目中应该跳转到详情页面或打开模态框
        }
        
        // 编辑公告
        function editAnnouncement(id) {
            // 先获取公告详情
            fetch(`http://127.0.0.1:8000/api/announcements/${id}/`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                credentials: 'include'
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                // 设置默认发布时间为当前时间
                const now = new Date();
                const formattedDateTime = now.toISOString().slice(0, 16); // 格式化为YYYY-MM-DDTHH:MM
                
                // 重置表单
                document.getElementById('announcement-form').reset();
                document.getElementById('publish-date').value = formattedDateTime;
                
                // 填充表单
                document.getElementById('announcement-title').value = data.title;
                document.getElementById('announcement-content').value = data.content;
                document.getElementById('announcement-type').value = data.type;
                
                // 填充状态字段
                const statusField = document.getElementById('announcement-status');
                if (statusField) {
                    statusField.value = data.status || 'published';
                }
                
                // 设置发布日期
                if (data.publish_date) {
                    const publishDateInput = document.getElementById('publish-date');
                    if (publishDateInput) {
                        publishDateInput.value = formatDateForInput(data.publish_date);
                    }
                }
                
                // 设置过期时间
                if (data.expire_date) {
                    const expireDateInput = document.getElementById('expire-date');
                    if (expireDateInput) {
                        expireDateInput.value = formatDateForInput(data.expire_date);
                    }
                }
                
                document.getElementById('is-sticky').checked = data.is_sticky;
                
                // 显示模态框
                const publishModal = document.getElementById('publish-modal');
                if (publishModal) {
                    publishModal.classList.remove('hidden');
                    document.body.style.overflow = 'hidden'; // 阻止背景滚动
                }
                
                // 保存要编辑的ID
                document.getElementById('announcement-form').dataset.announcementId = id;
                document.getElementById('submit-announcement').textContent = '更新公告';
            })
            .catch(error => {
                console.error('获取公告详情失败:', error);
                alert('获取公告详情失败，请重试');
            });
        }
        
        // 格式化日期用于输入框
        function formatDateForInput(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toISOString().slice(0, 16); // 格式化为YYYY-MM-DDTHH:MM
        }
        // 删除公告
        function deleteAnnouncement(id) {
            if (confirm(`确定要删除该公告吗？`)) {
                fetch(`http://127.0.0.1:8000/api/announcements/${id}/`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    credentials: 'include'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除失败');
                    }
                    // 删除成功后重新加载数据
                    loadAnnouncements();
                })
                .catch(error => {
                    console.error('删除公告失败:', error);
                    alert('删除失败，请稍后重试');
                });
            }
        }
        
        <!-- 发布公告模态框HTML结构 -->
        const publishModalHTML = `
            <div id="publish-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
                <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
                    <!-- 背景遮罩 -->
                    <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                        <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
                    </div>
                    
                    <!-- 模态框内容 -->
                    <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
                    <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full">
                        <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                            <div class="sm:flex sm:items-start">
                                <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                                    <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                                        发布公告
                                    </h3>
                                    
                                    <!-- 公告表单 -->
                                    <form id="announcement-form" class="space-y-4">
                                        <!-- 公告标题 -->
                                        <div>
                                            <label for="announcement-title" class="block text-sm font-medium text-gray-700 mb-1">
                                                公告标题 <span class="text-red-500">*</span>
                                            </label>
                                            <input type="text" id="announcement-title" name="title" 
                                                class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md px-3 py-2" 
                                                placeholder="请输入公告标题" required>
                                            <div id="title-error" class="mt-1 text-sm text-red-600 hidden">请输入公告标题</div>
                                        </div>
                                        
                                        <!-- 公告类型 -->
                                        <div>
                                            <label for="announcement-type" class="block text-sm font-medium text-gray-700 mb-1">
                                                公告类型 <span class="text-red-500">*</span>
                                            </label>
                                            <select id="announcement-type" name="type" 
                                                class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md px-3 py-2" required>
                                                <option value="">请选择公告类型</option>
                                                <option value="notice">通知公告</option>
                                                <option value="event">活动通知</option>
                                                <option value="bill">缴费通知</option>
                                                <option value="maintenance">维修公告</option>
                                                <option value="other">其他公告</option>
                                            </select>
                                            <div id="type-error" class="mt-1 text-sm text-red-600 hidden">请选择公告类型</div>
                                        </div>

                                        <!-- 公告状态 -->
                                        <div>
                                            <label for="announcement-status" class="block text-sm font-medium text-gray-700 mb-1">
                                                公告状态 <span class="text-red-500">*</span>
                                            </label>
                                            <select id="announcement-status" name="status" 
                                                class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md px-3 py-2" required>
                                                <option value="draft">草稿</option>
                                                <option value="published" selected>已发布</option>
                                                <option value="expired">已过期</option>
                                            </select>
                                            <div id="status-error" class="mt-1 text-sm text-red-600 hidden">请选择公告状态</div>
                                        </div>
                                        
                                        <!-- 公告内容 -->
                                        <div>
                                            <label for="announcement-content" class="block text-sm font-medium text-gray-700 mb-1">
                                                公告内容 <span class="text-red-500">*</span>
                                            </label>
                                            <textarea id="announcement-content" name="content" rows="6" 
                                                class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md px-3 py-2" 
                                                placeholder="请输入公告内容" required></textarea>
                                            <div id="content-error" class="mt-1 text-sm text-red-600 hidden">请输入公告内容</div>
                                        </div>
                                        
                                        <!-- 发布日期 -->
                                        <div>
                                            <label for="publish-date" class="block text-sm font-medium text-gray-700 mb-1">
                                                发布日期 <span class="text-red-500">*</span>
                                            </label>
                                            <input type="datetime-local" id="publish-date" name="publish_date" 
                                                class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md px-3 py-2" required>
                                        </div>
                                        
                                        <!-- 截止日期 -->
                                        <div>
                                            <label for="expire-date" class="block text-sm font-medium text-gray-700 mb-1">
                                                截止日期
                                            </label>
                                            <input type="datetime-local" id="expire-date" name="expire_date" 
                                                class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md px-3 py-2">
                                        </div>
                                        

                                        
                                        <!-- 是否置顶 -->
                                        <div class="flex items-center">
                                            <input id="is-sticky" name="is_sticky" type="checkbox" 
                                                class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                                            <label for="is-sticky" class="ml-2 block text-sm text-gray-700">
                                                置顶公告
                                            </label>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                            <button type="button" id="submit-announcement" 
                                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                                发布公告
                            </button>
                            <button type="button" id="cancel-announcement" 
                                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 将模态框添加到页面
        document.body.insertAdjacentHTML('beforeend', publishModalHTML);
        
        // 获取模态框元素
        const publishModal = document.getElementById('publish-modal');
        const cancelAnnouncementBtn = document.getElementById('cancel-announcement');
        
        // 发布公告按钮点击事件
        const publishButton = document.querySelector('.btn-primary');
        if (publishButton) {
            publishButton.addEventListener('click', function() {
                // 设置默认发布时间为当前时间
                const now = new Date();
                const formattedDateTime = now.toISOString().slice(0, 16); // 格式化为YYYY-MM-DDTHH:MM
                document.getElementById('publish-date').value = formattedDateTime;
                
                // 重置表单
                document.getElementById('announcement-form').reset();
                document.getElementById('publish-date').value = formattedDateTime;
                
                // 隐藏错误提示
                hideAllErrors();
                
                // 显示模态框
                publishModal.classList.remove('hidden');
                document.body.style.overflow = 'hidden'; // 阻止背景滚动
            });
        }
        
        // 取消按钮点击事件
        if (cancelAnnouncementBtn) {
            cancelAnnouncementBtn.addEventListener('click', function() {
                closeModal();
            });
        }
        
        // 点击背景关闭模态框
        if (publishModal) {
            publishModal.addEventListener('click', function(e) {
                if (e.target === publishModal) {
                    closeModal();
                }
            });
        }
        
        // 关闭模态框函数
        function closeModal() {
            publishModal.classList.add('hidden');
            document.body.style.overflow = ''; // 恢复背景滚动
        }
        
        // 隐藏所有错误提示
        function hideAllErrors() {
            document.getElementById('title-error').classList.add('hidden');
            document.getElementById('type-error').classList.add('hidden');
            document.getElementById('content-error').classList.add('hidden');
        }
        
        // 表单验证函数
        function validateForm() {
            let isValid = true;
            hideAllErrors();
            
            // 验证标题
            const title = document.getElementById('announcement-title').value.trim();
            if (!title) {
                document.getElementById('title-error').classList.remove('hidden');
                isValid = false;
            }
            
            // 验证类型
            const type = document.getElementById('announcement-type').value;
            if (!type) {
                document.getElementById('type-error').classList.remove('hidden');
                isValid = false;
            }
            
            // 验证公告状态
            const status = document.getElementById('announcement-status').value;
            if (!status) {
                document.getElementById('status-error').classList.remove('hidden');
                isValid = false;
            }
            
            // 验证内容
            const content = document.getElementById('announcement-content').value.trim();
            if (!content) {
                document.getElementById('content-error').classList.remove('hidden');
                isValid = false;
            }
            
            // 验证发布日期
            const publishDate = document.getElementById('publish-date').value;
            if (!publishDate) {
                alert('请设置发布日期');
                isValid = false;
            }
            
            // 验证截止日期（如果有设置）
            const expireDate = document.getElementById('expire-date').value;
            if (expireDate && publishDate) {
                if (new Date(expireDate) <= new Date(publishDate)) {
                    alert('截止日期必须晚于发布日期');
                    isValid = false;
                }
            }
            
            return isValid;
        }
        
        // 添加表单验证事件监听
        const submitButton = document.getElementById('submit-announcement');
        if (submitButton) {
            submitButton.addEventListener('click', function() {
                // 先验证表单
                if (validateForm()) {
                    // 收集表单数据
            const formData = {
                title: document.getElementById('announcement-title').value.trim(),
                type: document.getElementById('announcement-type').value,
                content: document.getElementById('announcement-content').value.trim(),
                status: document.getElementById('announcement-status').value,
                publish_date: document.getElementById('publish-date').value,
                is_sticky: document.getElementById('is-sticky').checked,
                expire_date: document.getElementById('expire-date').value || null
                // publisher字段由后端自动设置为当前登录用户，无需前端提供
            };
                    
                    // 发送POST请求
                    submitAnnouncement(formData);
                }
            });
        }
        
        // 提交公告到API
        async function submitAnnouncement(formData) {
            try {
                // 显示加载状态
                submitButton.disabled = true;
                submitButton.textContent = '发布中...';
                
                // 发送POST请求到API
                const response = await fetch('/api/announcements/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken() // 获取CSRF令牌
                    },
                    body: JSON.stringify(formData)
                });
                
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.textContent = '发布公告';
                
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                
                const result = await response.json();
                
                // 成功提示
                alert('公告发布成功！');
                
                // 关闭模态框
                closeModal();
                
                // 重新加载公告列表
                loadAnnouncements();
                
            } catch (error) {
                console.error('发布公告失败:', error);
                alert('发布公告失败，请稍后重试。\n' + error.message);
                
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.textContent = '发布公告';
            }
        }
        
        // 获取CSRF令牌
        function getCSRFToken() {
            const cookieValue = document.cookie
                .split('; ')
                .find(row => row.startsWith('csrftoken='))
                ?.split('=')[1];
            return cookieValue || '';
        }
    </script>
</body>
</html>